// pub fn time_info(time: &str) -> String {
//     todo!()
// }
use std::fs::File;
use std::io::{self, BufRead};
use std::path::Path;


pub fn time_info(time: &str) -> String {
    // 解析输入的年月日
    let parts: Vec<i32> = time.split('-')
        .map(|x| x.parse().unwrap())
        .collect();
    let (year, month, day) = (parts[0], parts[1], parts[2]);

    // 读取春节日期数据
    // let spring_dates = load_spring_dates("chunjie.txt").unwrap();

    // 计算是第几周
    let week = calculate_week(year, month, day);
    
    // 计算当年剩余天数 这个没问题
    let days_left = calculate_days_left(year, month, day);
    
    // 计算到春节的天数
    let days_to_spring = calculate_days_to_spring(year, month, day);
    
    format!("{},{},{}", week, days_left, days_to_spring)
}


// 计算指定日期是第几周
fn calculate_week(year: i32, month: i32, day: i32) -> i32 {
    // 计算1月1日是周几(1-7表示周一到周日)
    let jan1_weekday = get_weekday(year, 1, 1);
    
    // 计算目标日期是该年第几天
    let days_from_year_start = days_from_year_start(year, month, day);
    
    // 如果1月1日是周四或之前，那么这一周就是第1周
    // 如果1月1日是周五或之后，那么这一周属于上一年的最后一周
    let first_week_offset = if jan1_weekday <= 4 { 0 } else { -1 };

    // 计算当前日期是周几
    let current_weekday = get_weekday(year, month, day);

    // 如果是12月的最后几天，需要判断是否属于下一年第一周
    if month == 12 && day >= 29 {
        let next_year_jan1_weekday = get_weekday(year + 1, 1, 1);
        if next_year_jan1_weekday <= 4 && current_weekday <= next_year_jan1_weekday {
            return 1;  // 属于下一年第一周
        }
    }

    // 如果是1月的前几天，需要判断是否属于上一年最后一周
    if month == 1 && day <= 3 {
        if jan1_weekday > 4 {
            return calculate_last_week_of_year(year - 1);
        }
    }
    
    // 修正后的周数计算公式
    let week = (days_from_year_start + jan1_weekday - 2) / 7 + 1 + first_week_offset;
    
    if week <= 0 {
        // 属于上一年的最后一周
        calculate_last_week_of_year(year - 1)
    } else {
        week
    }
}

// 计算某年的最后一周
fn calculate_last_week_of_year(year: i32) -> i32 {
    // 计算当年1月1日是周几
    let jan1_weekday = get_weekday(year, 1, 1);
    
    // 计算当年总天数
    let year_days = if is_leap_year(year) { 366 } else { 365 };
    
    // 计算最后一天是周几
    let last_day_weekday = get_weekday(year, 12, 31);
    
    // 计算最后一周
    let week = (year_days + jan1_weekday - 2) / 7 + 1;
    
    // 如果最后一天是周四或之后，那么是这一年的最后一周
    // 否则算作下一年的第一周
    if last_day_weekday >= 4 {
        week
    } else {
        let next_year_jan1_weekday = get_weekday(year + 1, 1, 1);
        if next_year_jan1_weekday <= 4 {
            1  // 属于下一年第一周
        } else {
            week  // 属于本年最后一周
        }
    }
}

// 使用蔡勒公式计算星期几(1-7表示周一到周日)
fn get_weekday(year: i32, month: i32, day: i32) -> i32 {
    let (y, m) = if month <= 2 {
        (year - 1, month + 12)
    } else {
        (year, month)
    };
    
    let c = y / 100;
    let y = y % 100;
    
    let w = (y + y/4 + c/4 - 2*c + 26*(m+1)/10 + day - 1) % 7;
    let w = (w + 7) % 7;
    if w == 0 { 7 } else { w }
}

// 计算从年初到指定日期的天数
fn days_from_year_start(year: i32, month: i32, day: i32) -> i32 {
    let month_days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
    let mut days = day;
    
    for m in 0..(month-1) {
        days += if m == 1 && is_leap_year(year) {
            29
        } else {
            month_days[m as usize]
        };
    }
    
    days
}

// 判断是否闰年
fn is_leap_year(year: i32) -> bool {
    (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)
}




// 计算当年剩余天数
fn calculate_days_left(year: i32, month: i32, day: i32) -> i32 {
    let is_leap = is_leap_year(year);
    let total_days = if is_leap { 366 } else { 365 };
    total_days - days_from_year_start(year, month, day)
}

// 读取春节日期文件
fn load_spring_festivals() -> Vec<(i32, i32, i32)> {
    let mut festivals = Vec::new();
    if let Ok(lines) = read_lines("chunjie.txt") {
        for line in lines.flatten() {
            let parts: Vec<&str> = line.split('-').collect();
            if parts.len() == 3 {
                let year = parts[0].parse().unwrap_or(0);
                let month = parts[1].parse().unwrap_or(0);
                let day = parts[2].parse().unwrap_or(0);
                festivals.push((year, month, day));
            }
        }
    }
    festivals
}

// 计算到春节的天数
fn calculate_days_to_spring(year: i32, month: i32, day: i32) -> i32 {
    let festivals = load_spring_festivals();
    
    // 找到下一个春节日期
    let next_spring = festivals.iter()
        .find(|&&(y, m, d)| {
            if y == year {
                // 如果是同年，则月份和日期都要大于当前日期
                (m > month) || (m == month && d > day)
            } else {
                y > year
            }
        })
        .copied()
        .unwrap_or((year + 1, 1, 29)); // 如果找不到，使用默认值
    
    if next_spring.0 == year {
        // 如果春节在同一年
        days_between_dates(year, month, day, 
                         next_spring.0, 
                         next_spring.1, 
                         next_spring.2)
    } else {
        // 如果春节在下一年
        let days_left = calculate_days_left(year, month, day);
        let days_to_spring = days_from_year_start(next_spring.0, next_spring.1, next_spring.2);
        days_left + days_to_spring - 1 // 减1是因为不包含当天
    }
}

// 读取文件的辅助函数
fn read_lines<P>(filename: P) -> io::Result<io::Lines<io::BufReader<File>>>
where P: AsRef<Path> {
    let file = File::open(filename)?;
    Ok(io::BufReader::new(file).lines())
}

// 计算两个日期之间的天数
fn days_between_dates(y1: i32, m1: i32, d1: i32, y2: i32, m2: i32, d2: i32) -> i32 {
    if y1 == y2 {
        days_from_year_start(y2, m2, d2) - days_from_year_start(y1, m1, d1) -1
    } else {
        let days_left = calculate_days_left(y1, m1, d1);
        let days_to_spring = days_from_year_start(y2, m2, d2);
        days_left + days_to_spring - 1 // 减1是因为不包含当天
    }
}

// 计算两个日期之间的天数
// fn days_between_dates(y1: i32, m1: i32, d1: i32, y2: i32, m2: i32, d2: i32) -> i32 {
//     days_from_year_start(y2, m2, d2) - days_from_year_start(y1, m1, d1)
// }

